package org.example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        Arrays.sort(nums);
        for(int i = 0; i < nums.length; i++){
            if(i != 0 && nums[i - 1] == nums[i]){
                continue;
            }
            int target = 0 - nums[i];
            int l = i + 1, r = nums.length - 1;
            while(l < r){

                if(nums[l] + nums[r] == target){
                    List<Integer> tmp = new ArrayList<>();
                    tmp.add(nums[i]);
                    tmp.add(nums[l]);
                    tmp.add(nums[r]);
                    ans.add(tmp);
                    l++;
                    r--;
                    while(l < r && nums[l] == nums[l-1])
                        l++;
                    while(l < r && nums[r] == nums[r+1])
                        r--;
                }else if(nums[l] + nums[r] < target){
                    l++;
                    while(l < r && nums[l] == nums[l-1])
                        l++;
                }else{
                    r--;
                    while(l < r && nums[r] == nums[r+1])
                        r--;
                }
            }
        }
        return ans;
    }
}
